"""
@Author：WangYuXiang
@E-mile：Hill@3io.cc
@CreateTime：2021/3/24 16:26
@DependencyLibrary：无
@MainFunction：无
@FileDoc： 
    __init__.py
    文件说明
@ChangeHistory:
    datetime action why
    example:
    2021/3/24 16:26 change 'Fix bug'
        
"""
import logging
import importlib
from pathlib import Path

from sanic import Sanic
from sanic_cors import CORS
from sanic_plugin_toolkit import SanicPluginRealm
from tortoise.contrib.sanic import register_tortoise
from srf_app_helper import apps_helper
from sanic_rest_framework.request import SRFRequest
from settings import APP_NAME

logging.basicConfig(filename="access.log")

cofing_name = 'settings.py'

def create_app():
    """工厂函数"""
    sanic_app = Sanic(name=APP_NAME, request_class=SRFRequest)
    sanic_app.update_config(Path.cwd() / cofing_name)
    CORS(sanic_app)
    realm = SanicPluginRealm(sanic_app)
    realm.register_plugin(apps_helper)
    register_tortoise(
        sanic_app, db_url=sanic_app.config.get('DB_CONNECT_STR'), modules=apps_helper.models
        # , generate_schemas=False
    )
    return sanic_app


app = create_app()

# 此为迁移配置
TORTOISE_ORM = {
    "connections": {"default": app.config.get('DB_CONNECT_STR')},
    "apps": {
        "models": {
            "models": ['aerich.models'],
            "default_connection": "default",
        },
    },
}
for name, val in apps_helper.models.items():
    TORTOISE_ORM['apps'][name] = {
        "models": val,
        "default_connection": "default",
    }

# 延时加载
importlib.import_module('signals')
importlib.import_module('handle_exception')
